const app = getApp()

Component({
  options: {
    pureDataPattern: /^_/ // 指定所有 _ 开头的数据字段为纯数据字段
  },

  data: {
    longitude: 0,
    latitude: 0,
    markers: [],
    _map: wx.createMapContext('map')
  },

  lifetimes: {
    attached() {
      this.loadData()
    },
    ready() {
      wx.getLocation({
        type: 'wgs84',
        success: (res) => {
          let {
            longitude,
            latitude
          } = res
  
          this.setData({
            longitude,
            latitude
          })
        }
      })
  
      this.loadData()
    }
  },

  pageLifetimes: {
    show() {
      this.loadData()
    }
  },

  methods: {
    loadData() {
      app.minipet.get({
        success: (res) => {
          const markers = res.data.map(value => {
            let {
              _id,
              latitude,
              longitude,
              message,
              type
            } = value
  
            return {
              id: _id,
              latitude,
              longitude,
              title: message,
              iconPath: `/resources/${type}.png`,
              width: 40,
              height: 40
            }
          })
  
          this.setData({
            markers
          })
        }
      })
    },
  
    handleLocationTap() {
      this.map.moveToLocation()
    },
  
    handlePublishTap() {
      wx.navigateTo({
        url: '/components/publish/publish',
      })
    },
  
    handleMarkerTap(e) {
      app.markerId = e.markerId

      wx.navigateTo({
        url: '/components/detail/detail'
      })
    }
  }
})